const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    /* seeting */
    setting: null,
    userData: null,
    userSign: null,
    loginUser: null
  },
  userInfo: {
    username: "",
    passworld: ""
  },
  formSubmit: function (e) {
    //console.log(e.detail.value)
    var info = e.detail.value;
    if (!info.username || !info.password) {
      wx.showToast({
        title: '输入为空',
        icon: 'loading',
        duration: 1000
      })
    } else {
      console.log('进入登录方法')
      console.log(info)
      this.loginIn(info)
    }
  },

  loginIn: function (data) {
    console.log(data)
    var that = this;

    if (!app.globalData.userInfo) {
      wx.showModal({
        title: '提示',
        content: '请在微信授权页面点击允许，否则部分功能可能无法使用，是否重新授权？',
        showCancel: true,
        cancelText: "否",
        confirmText: "是",
        success: function (res) {
          if (res.confirm) {
            if (wx.openSetting) {//当前微信的版本 ，是否支持openSetting
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userInfo"]) {//如果用户重新同意了授权登录
                    wx.getUserInfo({//跟上面的wx.getUserInfo  sucess处理逻辑一样
                      success: function (res) {
                        app.globalData.userInfo = res.userInfo;
                        console.log('//如果用户重新同意了授权登录');
                        console.log(app.globalData.userInfo)
                        that.goLogin(data);
                      }
                    })
                  } else {//用户还是拒绝
                   
                    var userInfo = {
                      avatarUrl: '',
                      nickName: '',
                      gender: 0,
                      city: ''
                    }

                    app.globalData.userInfo = userInfo,
                    that.goLogin(data);
                  }
                },
                fail: function () {//调用失败，授权登录不成功

                }
              })
            }else{
              
            }
          } else if (res.cancel) {
            console.log('===============取消了========================')
            //用户还是拒绝
            var userInfo = {
              avatarUrl: '',
              nickName: '',
              gender: 0,
              city: ''
            }
            
            app.globalData.userInfo = userInfo,
            console.log(app.globalData.userInfo)
            that.goLogin(data);
          }
        }
      })
    } else {
      that.goLogin(data);
    }
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.getUserInfo({
      success: res => {
        // 可以将 res 发送给后台解码出 unionId
        app.globalData.userInfo = res.userInfo
        console.log('=====index页面获取userInfo====')
        console.log(app.globalData.userInfo)
      }
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
  ,

  formReset: function () {
    console.log('form发生了reset事件')
  }
  ,
  goLogin: function (data) {
    //显示加载按钮
    wx.showLoading({
      title: 'loading',
      mask: true
    })
    console.log('##########################################')
    console.log(app.globalData.userInfo);
    wx.request({
      url: 'https://www.zuoye123.com/n_cloudmate/weixin/binduserid',
      data: {
        email: data.username,
        password: data.password,
        openid: app.globalData.openid,
        unionid: app.globalData.unionid,
        headimgurl: app.globalData.userInfo.avatarUrl,
        nickname: app.globalData.userInfo.nickName,
        sex: app.globalData.userInfo.gender,
        city: app.globalData.userInfo.city
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {

        console.log(res)
        var header = res.header
        var cookie = null
        if (!!header['Set-Cookie']) {
          cookie = header['Set-Cookie']
        }
        if (!!header['set-cookie']) {
          cookie = header['set-cookie']
        }

        console.log(cookie)
        wx.hideLoading()

        console.log('================login res=============')
        console.log(res.data)

        if (res.data.errorCode == 0) {
          //赋值到系统常量
          app.globalData.userId = res.data.userId;
          app.loginUser = res.data.loginUser[0];

          console.log('绑定账号成功：userId==' + app.globalData.userId);
          console.log('##########app.loginUser##############');
          console.log(app.loginUser);
          app.userSign = data;

          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              app.toIndex();
            }
          })
        } else {
          //弹出提示，用户名或者密码错误
          wx.showModal({
            title: '账号或密码错误！',
            content: '',
            showCancel: false
          })
        }
      },
      fail: function (res) {
        console.log("fail")
        wx.hideLoading()
        app.loadFail()
      }
    })
  }
})